package com.zzl.bonds.ticket.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzl.bonds.ticket.constant.type.CreditTypeEnum;
import com.zzl.bonds.ticket.dao.CoreEnterpriseCredidataDao;
import com.zzl.bonds.ticket.dto.CoreEnterpriseCredidataAddDto;
import com.zzl.bonds.ticket.dto.CoreEnterpriseCredidataUpdateDto;
import com.zzl.bonds.ticket.entity.EnterpriseCreditDataEntity;
import com.zzl.bonds.ticket.service.CoreEnterpriseCredidataService;
import com.zzl.general.common.exception.SysException;
import com.zzl.general.common.serurity.entity.User;
import com.zzl.general.common.utils.PageUtils;
import com.zzl.general.common.utils.Query;
import com.zzl.general.common.utils.UuidUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 核心企业授信资料表
 *
 * @author sunpp
 * @date 2022-02-16 11:14:07
 */
@Service("coreEnterpriseCredidataService")
public class CoreEnterpriseCredidataServiceImpl extends ServiceImpl<CoreEnterpriseCredidataDao, EnterpriseCreditDataEntity> implements CoreEnterpriseCredidataService {

    /**
     * 分页查询
     *
     * @param params 查询参数
     * @return 分页数据
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<EnterpriseCreditDataEntity> page = this.page(
                new Query<EnterpriseCreditDataEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    /**
     * 修改核心企业的授信资料
     *
     * @param list 授信资料
     */
    @Override
    public void addUpdateCreditDatas(List<EnterpriseCreditDataEntity> list, String coreCreditId, User user) throws SysException {
        QueryWrapper<EnterpriseCreditDataEntity> deleteWrapper = new QueryWrapper<>();
        deleteWrapper.lambda().eq(EnterpriseCreditDataEntity::getCreditId, coreCreditId);
        this.remove(deleteWrapper);
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        for (EnterpriseCreditDataEntity entity : list) {
            entity.setCreditId(coreCreditId);
            entity.setId(UuidUtils.UUID());
            entity.setCreatorId(user.getId());
            entity.setCreateTime(new Date());
            entity.setEnterpriseId(user.getEnterpriseId());
            entity.setOrgId(user.getOrgId());
            if (ObjectUtils.isEmpty(entity.getDataAddress())) {
                throw new SysException("资料地址不能为空");
            }
            if (ObjectUtils.isEmpty(entity.getFileName())) {
                throw new SysException("文件名称不能为空");
            }
        }
        this.saveBatch(list);
    }


    @Override
    public Map<String, List<EnterpriseCreditDataEntity>> getByCoreEnterpriseIds(List<String> ids) {
        QueryWrapper<EnterpriseCreditDataEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(EnterpriseCreditDataEntity::getCreditId, ids);
        List<EnterpriseCreditDataEntity> list = this.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        return list.stream().collect(Collectors.groupingBy(EnterpriseCreditDataEntity::getCreditId));
    }

    /**
     * 新增
     *
     * @param coreEnterpriseCredidataAddDto 新增实体
     * @param user                          当前登录用户
     * @throws SysException 业务异常
     */
    @Override
    public void saveCoreEnterpriseCredidata(CoreEnterpriseCredidataAddDto coreEnterpriseCredidataAddDto, User user) throws SysException {
        EnterpriseCreditDataEntity coreEnterpriseCredidataEntity = new EnterpriseCreditDataEntity();
        BeanUtils.copyProperties(coreEnterpriseCredidataAddDto, coreEnterpriseCredidataEntity);
        coreEnterpriseCredidataEntity.setCreatorId(user.getId());
        if (!this.save(coreEnterpriseCredidataEntity)) {
            throw new SysException("A00001", "保存失败！");
        }
    }

    /**
     * 修改
     *
     * @param coreEnterpriseCredidataUpdateDto 修改实体
     * @param user                             当前登录用户
     * @throws SysException 业务异常
     */
    @Override
    public void updateCoreEnterpriseCredidataById(CoreEnterpriseCredidataUpdateDto coreEnterpriseCredidataUpdateDto, User user) throws SysException {
        EnterpriseCreditDataEntity coreEnterpriseCredidataEntity = new EnterpriseCreditDataEntity();
        BeanUtils.copyProperties(coreEnterpriseCredidataUpdateDto, coreEnterpriseCredidataEntity);
        coreEnterpriseCredidataEntity.setUpdaterId(user.getId());
        if (!this.updateById(coreEnterpriseCredidataEntity)) {
            throw new SysException("A00002", "修改失败！");
        }
    }

    /**
     * 新增授信资料
     *
     * @param files 授信文件
     * @param id    融资授信id
     * @param user  用户
     */
    @Override
    public void addCreditDatas(List<EnterpriseCreditDataEntity> files, String id, User user) throws SysException {
        QueryWrapper<EnterpriseCreditDataEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EnterpriseCreditDataEntity::getSupplierCreditId, id);
        List<EnterpriseCreditDataEntity> list = this.list(queryWrapper);
        //先删除，再添加
        if (!CollectionUtils.isEmpty(list)) {
            List<String> collect = list.stream().map(EnterpriseCreditDataEntity::getId).collect(Collectors.toList());
            this.baseMapper.deleteBatchIds(collect);
        }
        files.forEach(x -> {
            x.setId(UuidUtils.UUID());
            x.setEnterpriseId(user.getEnterpriseId());
            x.setOrgId(user.getOrgId());
            x.setUpdaterId(user.getId());
            x.setCreatorId(user.getId());
            x.setSupplierCreditId(id);
            x.setCreditType(CreditTypeEnum.FINANCE_CREDIT.getCode());
        });
        if (!this.saveBatch(files)) {
            throw new SysException("附件资料保存失败");
        }

    }

    /**
     * 查询授信额度的文件
     *
     * @param id   融资授信额度
     * @param code 授信类型，3 开立授信 4 融资授信
     * @return 授信额度的文件
     */
    @Override
    public List<EnterpriseCreditDataEntity> getCredidataBySupplierId(String id, Integer code) {
        QueryWrapper<EnterpriseCreditDataEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EnterpriseCreditDataEntity::getSupplierCreditId, id)
                .eq(EnterpriseCreditDataEntity::getCreditType, code);
        return this.list(queryWrapper);
    }

}